<?php
/**
 * User: Mykola B
 * Date: 3/1/13
 * Time: 7:13 PM
 */
class Settings
{
    private $settings;
    private $settings_file;
    private static $instance;

    private function __construct($settings_file) {
        if (!file_exists($settings_file)) {
            throw new Exception("Settings file $settings_file does not exist.");
        }
        $this->settings_file = realpath($settings_file);
        $this->settings = json_decode(file_get_contents($settings_file));
    }

    public static function getSettings($settings_file='src/settings.json') {
        if (empty(self::$instance)) {
            self::$instance = new Settings($settings_file);
        }
        return self::$instance;
    }

    public function __get($name) {
        if (isset($this->settings->$name)) {
            return $this->settings->$name;
        }
        return null;
    }

    public function __set($name, $value) {
        $this->settings->$name = $value;
    }

    public function save() {
        file_put_contents($this->settings_file, json_encode($this->settings));
    }

    public function __destruct() {
        $this->save();
    }
}
